import { computed } from "vue"
import { useTableV2 } from "./useTableV2"
import { useElMessageBox } from "@Tea/utils"
import { httpCommonHandle } from "@/utils/httpUtils"
import http from "@/api"
import { FN } from "@Tea/model"

/**
 * @use 
 * 将停用启用、以及操作停用启用抽离成 hook 返回一个promise，这个promise返回的是请求的结果
 * 
 * @attention 
 * 这个是 TableV2 的版本，仅仅适用于 V2 版本
 */
export function useEnable<O extends {
  enable: 0 | 1
}>({
  origin,
  tableName,
}: {
  origin: O,
  tableName: string,
}) {
  const { handleRadioRow, tableLoading } = useTableV2(tableName)

  const buttonFlag = computed(() => {
    return origin.enable ? '停用' : '启用'
  })

  const checkboxFlag = computed(() => {
    return origin.enable ? '启用' : '停用'
  })

  const handleEnable = <Row>(request: (data: Row) => ReturnType<typeof http>, onSuccess?: FN) => {
    return new Promise((resolve, reject) => {
      handleRadioRow<Row>((data) => {
        useElMessageBox({
          content: `确定要${buttonFlag.value}吗？`,
          thenCallback: async () => {
            const result = httpCommonHandle({
              loading: tableLoading,
              callBack: () => request(data),
              onSuccess
            })

            resolve(result)
          }
        })
      })
    })
  }

  return {
    buttonFlag,
    checkboxFlag,
    handleEnable
  }
}